package com.ebanma.cloud.interceptor;

import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ebanma.cloud.user.dao.po.User;
import com.ebanma.cloud.utils.JwtUtil;
import com.ebanma.cloud.utils.RedisUtil;
import com.ebanma.cloud.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author wangxin
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private JwtUtil jwtUtil;

    @Resource

    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {

        String token = request.getHeader("authorization");
        String uuid = null;
        String userJson=null;
        if (token != null && (uuid = jwtUtil.verifierJwtToken(token)) != null && StringUtils.isNotBlank(userJson=redisUtil.get(uuid))) {
            //存入用户信息，方便方法进行调取
            UserHolder.saveUser(JSONUtil.toBean(userJson,User.class));
            redisUtil.expire(uuid, 15L, TimeUnit.MINUTES);
            return true;
        } else {
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.write("用户没有登录");
            out.flush();
        }
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
        throws Exception {
        //删除信息，避免内存泄漏
        UserHolder.removeUser();
    }
}
